package com.im.socket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.im.config.SpringUtils;
import com.im.pojo.ImVideo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/index/{id}")
@Component
public class IndexWebSocket {

    private StringRedisTemplate redisTemplate = SpringUtils.getBean(StringRedisTemplate.class);

    // 存储用户与session
    public static ConcurrentHashMap<String, Session> user_hash = new ConcurrentHashMap<>();

    // 接收userId
    private String userId = null;

    public ConcurrentHashMap getSession() {
        return user_hash;
    }

    // 连接成功
    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id) {
        this.userId = id;

        user_hash.put(this.userId, session);
        Long userLogin = redisTemplate.opsForSet().add("userLogin", this.userId);
        System.out.println(this.userId + ": 连接成功");
    }

    // 连接关闭
    @OnClose
    public void onClose(Session session) {
        user_hash.remove(this.userId);
        Long userLogin = redisTemplate.opsForSet().remove("userLogin", this.userId);
        System.out.println(this.userId + ": 连接关闭");
    }

    // 收到客户端消息
    @OnMessage
    public void onMessage(String message, Session session) {
        ImVideo imVideo = JSON.parseObject(message, ImVideo.class);
        String receive_id = imVideo.getReceive_id();
        String video = imVideo.getVideo();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("code", 204);
        hashMap.put("data", video);
        String s = JSONObject.toJSONString(hashMap);
        try {
            Session receive_session = user_hash.get(receive_id);
            receive_session.getBasicRemote().sendText(s);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        ImVideo imVideo = JSON.parseObject(message, ImVideo.class);
//        Result result = new Result(ResultCode.VIDEO_YES, imVideo);
//        String s = JSONObject.toJSONString(result);
//        sendMessage(s, user_hash.get(imVideo.getReceive_id()));
    }

    // 发生错误
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println(error);
    }

    // 向客户端发送消息
    public void sendMessage(String message, Session toSession) {
        try {
            toSession.getBasicRemote().sendText(message);
        } catch (Exception e) {
            System.out.println("发送失败");
        }
    }

}